import {
  Text,
  StyleSheet,
  View,
  Image,
  TouchableOpacity,
  ScrollView,
} from "react-native";
import { WebView } from "react-native-webview";
import AsyncStorage from "@react-native-async-storage/async-storage";
import RenderHTML from "react-native-render-html";

import React, { useState, useRef } from "react";
import PageContainer from "@/components/PageContainer";
import useAppStateChange from "@/hooks/useAppStateChange";
import { useRouter, useLocalSearchParams } from "expo-router";
import { useTranslation } from "react-i18next";
import { ToastAPI } from "@/components/Toast";

export default function Market() {
  const appState = useAppStateChange();
  const params = useLocalSearchParams<{
    tradingSymbol: string;
    mainAssetSymbol: string;
    tradingId: string;
    secondaryAssetSymbol: string;
    price: string;
    changeRatio: string;
  }>();
  const router = useRouter();
  const { t } = useTranslation();

  const [assetProfile, setAssetProfile] = useState("");

  React.useEffect(() => {
    const loadData = async () => {
      try {
        const data = await AsyncStorage.getItem(
          `detailData_${params.tradingId}`
        );
        if (data) {
          setAssetProfile(data);
        }
      } catch (error) {
        console.error("读取数据失败:", error);
      }
    };
    loadData();
  }, [params.tradingId]);

  const webViewRef = useRef<WebView>(null);
  const [twoDataNum, setTwoDataNum] = useState<any>({
    highPrice: 0,
    lowPrice: 0,
    volume: 0,
    quoteVolume: 0,
  });
  // 定义处理函数映射
  const handlers: any = {
    getTradingSymbolFunction: () => {
      return {
        code: 0,
        msg: "getTradingSymbolFunction 处理成功",
        payload: { result: params?.tradingSymbol || "-" },
      };
    },
    get24hVolumeFunction: (data: any) => {
      setTwoDataNum(data);
      return {
        code: 0,
        msg: "get24hVolumeFunction 处理成功",
        payload: { result: null },
      };
    },
  };

  const onMessage = (event: any) => {
    try {
      const data = JSON.parse(event?.nativeEvent?.data || "{}");
      const { funcName, params, requestId } = data;

      // 根据 funcName 查找对应的处理函数
      const handler = handlers[funcName];
      let response;
      if (handler) {
        response = {
          requestId,
          ...handler(params),
        };
      } else {
        response = {
          requestId,
          code: 1,
          msg: `未找到处理函数: ${funcName}`,
          payload: null,
        };
      }

      if (webViewRef.current) {
        console.log(`向Web端响应[${funcName}]`, response);
        webViewRef.current.injectJavaScript(`
          (function() {
            const event = new MessageEvent('message', {
              data: ${JSON.stringify(response)}
            });
            window.dispatchEvent(event);
          })();
        `);
      }
    } catch (error) {
      console.error("解析消息出错", error);
    }
  };

  return (
    <PageContainer>
      <View className="bg-[#000] flex-1 p-[13px]">
        <View className="items-center flex-row h-[46px]">
          <TouchableOpacity onPress={() => router.back()}>
            <View className="flex-row gap-[10px] items-center">
              <Image
                source={require("@/assets/images/return-left.png")}
                className="w-[18px] h-[18px]"
              />
              <Text className="text-[18px] text-[#fff]">
                {params?.mainAssetSymbol || "-"} / {params.secondaryAssetSymbol}
              </Text>
            </View>
          </TouchableOpacity>
          <View className="flex-1 flex-row justify-center">
            <View className="flex-row items-center"></View>
          </View>
          <View className="w-[18px] h-[18px]"></View>
        </View>
        <ScrollView
          showsVerticalScrollIndicator={false}
          showsHorizontalScrollIndicator={false}
          style={{ flex: 1 }}
        >
          <View className="mt-[22px]">
            <View className="flex-row items-center gap-[10px] justify-between">
              <View>
                <Text className="text-[28px] text-[#0BBB73]">
                  ￥{params?.price}
                </Text>
                {/* <View>
                  <Text className="text-[#FFFFFF] text-[18px]">≈ ￥{params?.price}</Text>
                </View> */}
                <View>
                  <Text
                    className="text-[14px]"
                    style={{
                      color:
                        params.changeRatio && parseFloat(params.changeRatio) < 0
                          ? "#EA4474"
                          : "#0BBB73",
                    }}
                  >
                    {parseFloat(params.changeRatio) < 0 ? "" : "+"}
                    {params?.changeRatio}%
                  </Text>
                </View>
              </View>
              <View>
                <View>
                  <Text className="text-[#969698] text-[14px]">24h最高价</Text>
                  <Text className="text-[#fff] text-[16px]">
                    {twoDataNum?.highPrice}
                  </Text>
                </View>
                <View>
                  <Text className="text-[#969698] text-[14px]">24h最低价</Text>
                  <Text className="text-[#fff] text-[16px]">
                    {twoDataNum?.lowPrice}
                  </Text>
                </View>
              </View>
              <View>
                <View>
                  <Text className="text-[#969698] text-[14px]">
                    24h成交量({params?.mainAssetSymbol || "-"})
                  </Text>
                  <Text className="text-[#fff] text-[16px]">
                    {twoDataNum?.volume}
                  </Text>
                </View>
                <View>
                  <Text className="text-[#969698] text-[14px]">
                    24h成交额({params?.secondaryAssetSymbol || "-"})
                  </Text>
                  <Text className="text-[#fff] text-[16px]">
                    {twoDataNum?.quoteVolume}
                  </Text>
                </View>
              </View>
            </View>
          </View>
          <WebView
            source={{ uri: "https://rwxcoin.com/k-line.html" }}
            style={{ height: 359, marginTop: 10 }}
            ref={webViewRef}
            onMessage={onMessage}
            allowsBackForwardNavigationGestures={true}
            allowsLinkPreview={false}
          />
          <View className="mt-[22px]">
            <View className="gap-[10px] items-center flex-row">
              <Image
                source={require("@/assets/images/rectangle.png")}
                className="w-[3px] h-[18px]"
              ></Image>
              <Text className="text-[#fff] text-[18px] font-[bold]">
                币种名称是什么？
              </Text>
            </View>
            <RenderHTML
              source={{ html: assetProfile }}
              tagsStyles={{
                p: {
                  fontSize: 12,
                  color: "#9C9C9E",
                },
              }}
            />
          </View>
        </ScrollView>
      </View>
      <View
        style={{
          position: "absolute",
          bottom: 0,
          left: 0,
          right: 0,
          flexDirection: "row",
          gap: 10,
          backgroundColor: "#000",
          zIndex: 1000,
        }}
      >
        <View
          className="p-[20px]"
          style={{
            flexDirection: "row",
            gap: 10,
            flex: 1,
          }}
        >
          <TouchableOpacity
            style={{
              flex: 1,
              backgroundColor: "#0BBB73",
              borderRadius: 8,
              paddingVertical: 16,
              justifyContent: "center",
              alignItems: "center",
            }}
            onPress={() => {
              router.push({
                pathname: "/market/pay",
                params:{
                  ...params,
                  direction:0
                }
              });
            }}
          >
            <Text style={{ color: "white", fontSize: 18, fontWeight: "bold" }}>
              {t("market.buy")}
            </Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={{
              flex: 1,
              backgroundColor: "#EA4474",
              borderRadius: 8,
              paddingVertical: 16,
              justifyContent: "center",
              alignItems: "center",
            }}
            onPress={() => {
              router.push({
                pathname: "/market/pay",
                params:{
                  ...params,
                  direction:1
                }
              });
            }}
          >
            <Text style={{ color: "white", fontSize: 18, fontWeight: "bold" }}>
              {t("market.sell")}
            </Text>
          </TouchableOpacity>
        </View>
      </View>
    </PageContainer>
  );
}

const styles = StyleSheet.create({});
